from ctypes import cast, POINTER
from comtypes import CLSCTX_ALL
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume

# 获取默认音频设备
devices = AudioUtilities.GetSpeakers()
interface = devices.Activate(
    IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
volume = cast(interface, POINTER(IAudioEndpointVolume))


def unmute_system():
    """取消静音"""
    try:
        # 显式传入布尔值 False 代表取消静音，传入 None 作为 pguidEventContext 参数
        volume.SetMute(False, None)
        print("已取消静音")
    except Exception as e:
        print(f"取消静音时出错: {e}")


def set_system_volume(level=1.0):
    """
    设置系统音量 (0.0 到 1.0)
    level: float, 0.0 是静音，1.0 是最大音量
    """
    try:
        volume.SetMasterVolumeLevelScalar(level, None)
        print(f"系统音量已设为 {level * 100:.0f}%")
    except Exception as e:
        print(f"设置音量时出错: {e}")


def mute_system():
    """开启静音"""
    try:
        # 显式传入布尔值 True 代表开启静音，传入 None 作为 pguidEventContext 参数
        volume.SetMute(True, None)
        print("已开启静音")
    except Exception as e:
        print(f"开启静音时出错: {e}")


if __name__ == "__main__":
    unmute_system()
    set_system_volume(0.8)
    mute_system()
